using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using XRLib.INPUTHANDLER;

namespace firstrpg
{

    public enum dam_type
    {
        brute = 1,
        chemical = 2,
        radiation = 3,
        peircing = 4

    }
    public class client : Game
    {
        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;

        public static double seconds;
        public static Camera cam;
        public static Texture2D grasstexture;
        public static Texture2D space_texture;
        public static Texture2D human_texture;
        public static Texture2D inv_back_texture;
        public static Texture2D alert_say_back;
        public static SpriteFont defaultfont;
        public static SpriteFont mousefont;
        public static Texture2D[] item_texture = new Texture2D[1];
        public static Texture2D lightMask;
        public static List<string> strings = new List<string>();



        public static bodyContainer bodies;
        public static turfManager turfs;
        public static itemContainer items;

        public static int numAlertMessage = 20;
        public static alert_message[] Alert_Message = new alert_message[numAlertMessage];
        
        public static body mob = new body();
        public static short myPlayer = 0;       //the index of the body you control 

        public static int screenWidth = 800;
        public static int screenHeight = 600;
        public static readonly Rectangle ScreenRectangle;

        public static Texture2D blank;

        //effect test
        public static Effect effect1;
        RenderTarget2D lightsTarget;
        RenderTarget2D mainTarget;
        bool isDark = false;

        //particles
        particle_controller particleController;

        public client()
        {
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";

            Components.Add(new InputHandler(this));

            graphics.PreferredBackBufferWidth = screenWidth;
            graphics.PreferredBackBufferHeight = screenHeight;
            graphics.ApplyChanges();
            //base.Window.AllowUserResizing = true;
            alert_message.message_alert("construct and set backbuffer/screen size",Color.Tomato);

        }

        /// <summary>
        /// Called in draw, displays names under your mouse if your scrolled over a person
        /// </summary>
        protected void Display_Mouse_Names()
        {
            int x = (int)(InputHandler.mousePosition.X + cam.screenPosition.X);
            int y = (int)(InputHandler.mousePosition.Y + cam.screenPosition.Y);

            
            foreach (body b in cam.bodies_on_screen)
            {
                if (b==null) continue;
                if (cam.screenBounds.Contains((int)(b.position.X), (int)(b.position.Y)))
                {
                    Rectangle bodyB = new Rectangle((int)(b.position.X), (int)(b.position.Y), (int)(b.width+(cam.Zoom*10)), (int)(b.height+(cam.Zoom*10)));
                    
                    Vector2 textsize = (mousefont.MeasureString(b.name) * 0.5f);
                   
                    if (bodyB.Contains(x, y))
                        spriteBatch.DrawString(mousefont, b.name, new Vector2(b.position.X - ((float)Math.Round(textsize.X,0)), b.position.Y + (b.height * 0.5f)),
                            Color.White);
                }
            }


         //   Console.WriteLine(x);
           // Console.WriteLine(mob.position.X);
        }

        /// <summary>
        ///This function is called when a client runs the program for the first time
        ///<para>Connect to and create a body type, add it to the appropriate containers,
        ///and call body.login</para>
        /// </summary>
        protected void Login()
        {
            //do any junk here like phase the startup screen
            Console.Write("you login");

            alert_message.message_alert("somebody connected.");
            alert_message.message_alert("ip address is banned.");

            body you = new body();
            client.mob = you;

            bodies.Add(you);
            

            item.Create_Item_At_Location((int)mob.position.X, (int)mob.position.Y, itemtype.laser);
            item.Create_Item_At_Location((int)mob.position.X + 5, (int)mob.position.Y + 5, itemtype.laser);
            item.Create_Item_At_Location((int)mob.position.X + 10, (int)mob.position.Y + 10, itemtype.laser);
            

        }
        

        /// <summary>
        /// Calling base.Initialize will enumerate through any components
        /// and initialize them as well.
        /// </summary>
        protected override void Initialize()
        {
            Window.AllowUserResizing = true;
            
            base.IsMouseVisible = true;
            bodies = new bodyContainer();
            turfs = new turfManager();
            items = new itemContainer();
            cam = new Camera(GraphicsDevice.Viewport, Vector2.Zero);


            

            
            base.Initialize();

            Login();
        }

        /// <summary>
        /// Just a shortened method to load references
        /// </summary>
        /// <param name="st"></param>
        /// <returns></returns>
        protected Texture2D load_tex(string st) { return base.Content.Load<Texture2D>(@"" + st); }
        protected SpriteFont load_font(string st) { return base.Content.Load<SpriteFont>(@"fonts\" + st); }

        protected override void LoadContent()
        {
            
            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(GraphicsDevice);

            defaultfont                 = load_font("alert_2_font");
            mousefont                   = load_font("mouse_font");
            inv_back_texture            = load_tex("inv_back");
            space_texture               = load_tex("space_back");
            human_texture               = load_tex("human");
            alert_say_back              = load_tex("alertsayback");
            alert_message.alert_1_font  = load_font("alert_1_font");
            alert_message.alert_2_font  = load_font("alert_2_font");
            effect1 = base.Content.Load<Effect>("Effect1");
            lightMask = load_tex("lightmask2");

            var pp = GraphicsDevice.PresentationParameters;
            lightsTarget = new RenderTarget2D(
                GraphicsDevice, pp.BackBufferWidth, pp.BackBufferHeight);
            mainTarget = new RenderTarget2D(
                GraphicsDevice, pp.BackBufferWidth, pp.BackBufferHeight); 

            grasstexture = base.Content.Load<Texture2D>(@"turfs\grass");

            item_texture[0] = base.Content.Load<Texture2D>(@"locator");


            List<Texture2D> textures = new List<Texture2D>();
            textures.Add(Content.Load<Texture2D>("fireppp"));
            
            particleController = new particle_controller(textures, new Vector2(400, 240));

            blank = new Texture2D(GraphicsDevice, 1, 1, false, SurfaceFormat.Color);
            blank.SetData(new[] { Color.White });
            
        }

        protected override void UnloadContent()
        {
            // TODO: Unload any non ContentManager content here
        }

        protected void debug_input()
        {
            // Allows the game to exit
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
                this.Exit();
            if (InputHandler.KeyPressed(Keys.Escape))
                this.Exit();
            if (InputHandler.KeyPressed(Keys.A))
                alert_message.message_alert("you log in.");
            if (InputHandler.KeyPressed(Keys.B))
            {
                Console.WriteLine("You activate quick pickup");
                inventory_screen.QuickPickUp();
            }
            if (InputHandler.KeyPressed(Keys.C))
                mob.add_to_inv(null);
        }
        Vector2 lighto = new Vector2(100, 100);

        protected override void Update(GameTime gameTime)
        {
            seconds = gameTime.ElapsedGameTime.TotalSeconds;
            this.debug_input();
            /*
            particleController.EmitterLocation = new Vector2(InputHandler.mousePosition.X, InputHandler.mousePosition.Y);
            particleController.Update();
           */
            if (isDark)
            {
                lighto += new Vector2(1, 1);
                if (lighto.X > 500)
                    lighto.X = -100;
                if (lighto.Y > 500)
                    lighto.Y = -100;
            }
            foreach (turfs turf in turfs.active)
            {
                if (turf == null)
                    continue;
                if (turf.timeCreated + 3 < seconds)
                    turfs.Remove(turf);
            }
            bodies.Update(gameTime);
            items.Update(gameTime);
            base.Update(gameTime);

            
            if (cam != null)
                cam.Update(gameTime);
            
        }
        
        
       
        protected override void Draw(GameTime gameTime)
        {
            
            if (isDark)
            {
                GraphicsDevice.SetRenderTarget(lightsTarget);
                GraphicsDevice.Clear(Color.Black);//new Color(5,5,90));
                spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.Additive);
                //draw light mask where there should be torches etc...
                spriteBatch.Draw(lightMask, new Vector2(400 - cam.screenPosition.X, 100 - cam.screenPosition.Y), Color.White);
                spriteBatch.Draw(lightMask, new Vector2(200 - cam.screenPosition.X, 250 - cam.screenPosition.Y), Color.White);

                spriteBatch.Draw(lightMask,
                    new Vector2(InputHandler.mousePosition.X, InputHandler.mousePosition.Y), new Rectangle(0, 0, lightMask.Width, lightMask.Height),
                    Color.Violet,
                    0f, new Vector2(lightMask.Width * 0.5f, lightMask.Height * 0.5f), 1.0f, SpriteEffects.None, 0);

                spriteBatch.Draw(lightMask, new Vector2(lighto.X - cam.screenPosition.X, lighto.Y - cam.screenPosition.Y)
                    , Color.White);
                spriteBatch.End();
            }

            GraphicsDevice.SetRenderTarget(mainTarget);
            GraphicsDevice.Clear(Color.Transparent);

         
            spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, null, null,null, null, cam.Transform);
             cam.Draw(gameTime, spriteBatch);
            
            Display_Mouse_Names();
            
            spriteBatch.End();
            /*
            spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.NonPremultiplied,SamplerState.LinearClamp,DepthStencilState.DepthRead
                ,RasterizerState.CullCounterClockwise,null);
            particleController.Draw(spriteBatch);
            spriteBatch.End();
             */

            




            GraphicsDevice.SetRenderTarget(null);
            GraphicsDevice.Clear(Color.Black);
            if (isDark)
            {
                spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend);
            
                effect1.Parameters["lightMask"].SetValue(lightsTarget);
                effect1.CurrentTechnique.Passes[2].Apply();
                spriteBatch.End();

            }
            

            

            //draw the fade effects of alerts, only works in non premultiplied state
            spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.NonPremultiplied);
            spriteBatch.Draw(space_texture, new Rectangle(0, 0,
                GraphicsDevice.PresentationParameters.BackBufferWidth,
                GraphicsDevice.PresentationParameters.BackBufferHeight), Color.White);
            spriteBatch.Draw(mainTarget, Vector2.Zero, Color.White);

            inventory_screen.draw(spriteBatch);
            alert_message.draw_messages(spriteBatch, gameTime);
            spriteBatch.End();

            base.Draw(gameTime);


        }


    }
}

//dubsteps
//vaski             - you wouldn't understand
//hatcha & benga    - 10 tons heavy
//kill the noise    - my world
//trolley snatcha   - the future
//datsik            - GAME OVER (FT. FLUX PAVILLION)
//mark of the ninja game
//digidesign        - joker
//vaski             - bail out
//the fifth         - kryptic minds
//Ramadanman        - Offal 
//Borgore           - Borgore ina trouble
//Kromestar         - DemonSlayah
//Tes La Rok        - Darkness Falls Upon Us
//kryptic minds     - the things they left
//downlink          - emergency
//emalkay           - battlesuit
//my life with the thrill kill kult - waiting for mommie (jb's blackjack mix)
//emika             - count backwards (marcel dettmann remix)

///ideas
//FTL for inspiration, 
//players can fly small scout ships, and use teleporters to transfer supplies/crew across ships/stations
//ships can eject small pods, only operational in atmospheric systems - use to land on planets.
//strong teleports can beam to planets
//force field shields around ships/stations
